<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>百度地图绘制城市轨迹</title>
	<style>
		html,
		body,
		#container {
			width: 100%;
			height: 100%;
			margin: 0;
			padding: 0;
		}

		.anchorBL {
			display: none !important;
		}

		/* 修改标记点上文本的样式 */
		.BMapLabel {
			color: #010106 !important;
			font-size: 21px !important;
			border: 1px solid transparent !important;
			background-color: transparent !important;
			margin-left: 4px !important;
		}
	</style>

	<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=你百度的key">
	</script>
</head>

<body>
	<!-- <div id="container" style="width: 100%;height: 100%;"></div> -->
	<div id="containertest" style="width: 100%;height: 100%;"></div>
	<script>
		// 监听uni-app发送的消息
		let saveData = null
		let timer = null
		window.addEventListener('message', (event) => {
			// console.log('uniMsg 监听发送:', event, event.data.includes('fyxtoken'));
			// if (event.data.includes('fyxtoken')) {
			// 	if(timer) clearTimeout(timer)
			// 	let data = JSON.parse(event.data)
			// 	saveData = data
			// 	console.log('data', data)
			// 	document.getElementById('container').style.display = 'block'
			// 	document.getElementById('containertest').style.display = 'none'
			// 	start('container', data.startlatlon, data.endlatlon, data.logisticNode)
			// }
		});
		window.addEventListener('load', () => {
			console.log('页面加载完毕！');
			window.parent.postMessage({
				type: 'fyxwebload',
				text: "loaded"
			}, '*')
		})
		// if(saveData) {
		// 	document.getElementById('container').style.display = 'block'
		// 	document.getElementById('containertest').style.display = 'none'
		// 	start('container', saveData.startlatlon, saveData.endlatlon, saveData.logisticNode)
		// }
		// console.log('开始了', saveData)
		// 测试开始
		timer = setTimeout(() => {
		// 	// 汇总
		// 	// 1.测试没有任何数据
		// 	// let data = {}
			let data = {
                // 福建平潭南岛语族博物馆  119.768008,25.634362
                // 平潭北港村  19.834633,25.590122
                // 平潭东痒岛  119.895451,25.596625
				// 2. 测试起点和终点-没有途径点数据
				startlatlon: { // 3.测试起点
					lat: "25.634362",
					lng: "119.768008",
				},
				endlatlon: { // 4.测试终点
					lat: "25.596625",
					lng: "119.895451"
				},
				// 5.测试途径点数据
				logisticNode: [
					'平潭北港村'
				]
			}
			start('containertest', data.startlatlon, data.endlatlon, data.logisticNode)
		// 	// // 测试结束
		// 	document.getElementById('container').style.display = 'none'
		// 	document.getElementById('containertest').style.display = 'block'
		}, 2000);
		// 测试结束-真实环境需要注释
	</script>
	<script>
		const myStyleJson = [
			// 道路填充颜色描边颜色，不显示文字
			{
				"featureType": "road",
				"elementType": "labels.text.fill",
				"stylers": {
					"color": "#9e9e9fff"
				}
			}, {
				"featureType": "road",
				"elementType": "labels.text.stroke",
				"stylers": {
					"color": "#9e9e9fff"
				}
			}, {
				"featureType": "road",
				"elementType": "geometry.fill",
				"stylers": {
					"color": "#e0e0e6ff"
				}
			}, {
				"featureType": "road",
				"elementType": "geometry.stroke",
				"stylers": {
					"color": "#e0e0e6ff"
				}
			}, {
				"featureType": "road",
				"elementType": "labels",
				"stylers": {
					"visibility": "off"
				}
			}
		]
	</script>

	<script>
		// 偏移标记点位置
		const offsetMarker = (map, marker, offsetX, offsetY) => {
			// 获取当前地图的缩放级别和中心点  
			console.log('map', map)
			var zoom = map.getZoom();
			var center = map.getCenter();

			// 假设在低缩放级别时，每个经纬度单位大约对应的像素数（这个值需要调整）  
			var pixelsPerDegreeAtLowZoom = 100000; // 示例值，实际值可能不同  

			// 根据缩放级别调整像素每度的值（简化的方法）  
			var pixelsPerDegree = pixelsPerDegreeAtLowZoom / Math.pow(2, zoom - 10); // 假设以10级缩放为基准  

			// 计算经纬度偏移量（注意：纬度是向北增加的，所以y的正偏移应该加在lat上；经度是向东增加的，所以x的负偏移应该减在lng上）  
			var offsetLng = -offsetX / pixelsPerDegree; // 向左偏移，所以是负值  
			var offsetLat = offsetY / pixelsPerDegree;  // 向上偏移，所以是正值  

			// 获取当前标记点的经纬度  
			var point = marker.getPosition();

			// 计算新的经纬度坐标  
			var newLng = point.lng + offsetLng;
			var newLat = point.lat + offsetLat;

			// 设置标记点的新位置  
			marker.setPosition(new BMap.Point(newLng, newLat));
		}
		// 添加标注的点
		const addMarker = (map, point, name, imgUrl) => {
			var myIcon = new BMap.Icon(imgUrl, new BMap.Size(49, 56));//添加自定义图标
			myIcon.setImageSize(new BMap.Size(49, 56));//设置图标大小
			var marker = new BMap.Marker(point, { icon: myIcon });
			marker.disableDragging();//禁止拖拽

			// 创建标签  
			var label = new BMap.Label(name, {
				offset: new BMap.Size(8, 8), // 设置标签相对于标记图标的偏移量  
				style: {
					color: '#010106',
					fontSize: '21px',
					border: '1px solid transparent',
					fontWeight: 'bold'
				}
			});
			marker.setLabel(label); // 为标记设置标签

			// console.log('offsetMarker')
			offsetMarker(map, marker, -5, 5);

			map.addOverlay(marker);
			// 使用示例：将标记点向左上角偏移5像素  

		}
		// 动态设置中心点和缩放级别
		const setMapCenterZoom = (map, pointsList) => {
			console.log('setMapCenterZoom', pointsList)
			// 根据传入的pointsList点位转化为百度Point
			const mapPointsList = []
			pointsList.forEach(item => {
				mapPointsList.push(new BMap.Point(Number(item.longitude), Number(item.latitude)))
			})
			const centerPoint = map.getViewport(mapPointsList)
			// 初始化地图，设置中心点坐标和地图级别
			console.log('centerPoint', centerPoint, mapPointsList)
			map.centerAndZoom(centerPoint.center, centerPoint.zoom < 7 ? 7 : (centerPoint.zoom > 11 ? 11 : centerPoint.zoom))
		}
		const start = (id = 'container', startlatlon, endlatlon, logisticNode = []) => {
			var map = new BMap.Map(id);
			// map.setMapStyle({ styleJson: myStyleJson });

			// 监听地图加载完成事件  
			map.addEventListener("tilesloaded", () => {  
				console.log("zwq地图加载完成！");  
				// 你可以在这里执行其他操作，比如添加覆盖物等  
				window.parent.postMessage({
					type: 'fyxweb',
					text: "loaded"
				}, '*')
			}); 

			// 1.没有物流信息，默认北京经纬度
			if (!startlatlon && !endlatlon && logisticNode.length <= 0) {

				var beijingCenter = new BMap.Point(116.404, 39.915);
				map.centerAndZoom(beijingCenter, 7);
			} else {
				// 2.有途径点数据
				if (startlatlon && endlatlon && logisticNode.length > 0) {
					var startPoint0 = new BMap.Point(startlatlon.lng, startlatlon.lat);
					var startPoint1 = new BMap.Point(endlatlon.lng, endlatlon.lat);
					var cityPoints = []
					var points = []; // 存储经纬度点

					// 驾车路线规划
					var drivingRoute = new BMap.DrivingRoute(map, {
						renderOptions: {
							map: map,
							autoViewport: true,
							hideMarkers: true
						},
						onMarkersSet: (routes) => {
							// 清除原有标注 routes[0] 是起点 routes[routes.length-1] 是终点 routes[i].Um 是途经点，这个地方不同的百度地图api版本表示方式略有不同，以自己实际为准，自己debugger去看吧！
							for (var i = 0; i < routes.length; i++) {
								if (i == 0 || i == routes.length - 1) {
									console.log('起点或终点', routes[i])
									map.removeOverlay(routes[i].marker);
								} else {
									console.log('途径点', routes[i])
									map.removeOverlay(routes[i].an);
								}
							}
							//调用添加自定义标注方法，实现禁止标注拖拽
							addMarker(map, startPoint0, '产', 'start.png');
							addMarker(map, startPoint1, '终', 'end.png');
							console.log('cityPoints', cityPoints)
							for (var i = 0; i < cityPoints.length; i++) {
								addMarker(
									map,
									new BMap.Point(cityPoints[i].lng, cityPoints[i].lat)
									, '途', 'end.png');
							}
						},
						onPolylinesSet: function (routes) {
							//设置线条样式，线路分为几段
							for (var i = 0; i < routes.length; i++) {
								routes[i].getPolyline().setStrokeWeight(8);
								routes[i].getPolyline().setStrokeOpacity(1);
								routes[i].getPolyline().setStrokeColor("#066cc2");
							}
						},
						onSearchComplete: (results, status) => {
							console.log('status', status, BMAP_STATUS_SUCCESS)
							if (status === BMAP_STATUS_SUCCESS) {
							} else {
								console.error('路线规划失败: ', status);
							}
						}
					});
					var count = 0;
					// 根据名称获取城市地区经纬度
					const getCityLatLng = (city, callback) => {
						var myGeo = new BMap.Geocoder();
						myGeo.getPoint(city, function (point) {
							console.log(point)
							callback(point);

						},
							city);
					}
					logisticNode.forEach((city, index) => {
						getCityLatLng(city, function (point) {
							console.log('point', city, point)
							if (point) {
								point.name = city
								points[index] = point;
								cityPoints[index] = point;
							}
							count++;
							if (count === logisticNode.length) {
								console.log('logisticNode', cityPoints)
								let pointsList = [
									{
										longitude: startlatlon.lng,
										latitude: startlatlon.lat
									},
									{
										longitude: endlatlon.lng,
										latitude: endlatlon.lat
									},
								]
								cityPoints.forEach(item => {
									pointsList.push({
										longitude: item.lng,
										latitude: item.lat
									})
								})
								setMapCenterZoom(map, pointsList)
								var startPoint0 = new BMap.Point(startlatlon.lng, startlatlon.lat);
								var startPoint1 = new BMap.Point(endlatlon.lng, endlatlon.lat);
								if(cityPoints.length > 0) {
									drivingRoute.search(startPoint0, cityPoints[cityPoints.length - 1], {
										waypoints: cityPoints.slice(0, cityPoints.length - 1)
									});
								} else {
									drivingRoute.search(startPoint0, startPoint1);
								}
								
							}
						});
					});
				}
				// 标记起点和终点 或 起点 或 终点
				else {
					var startPoint0 = null
					var startPoint1 = null
					let list = []
					if (startlatlon) {
						startPoint0 = new BMap.Point(startlatlon.lng, startlatlon.lat);
						addMarker(map, startPoint0, '产', 'start.png');
						list.push({
							longitude: startlatlon.lng,
							latitude: startlatlon.lat
						},)
					}
					if (endlatlon) {
						startPoint1 = new BMap.Point(endlatlon.lng, endlatlon.lat);
						addMarker(map, startPoint1, '终', 'end.png')
						list.push({
							longitude: endlatlon.lng,
							latitude: endlatlon.lat
						})
					}
					if (startlatlon || endlatlon) {
						setMapCenterZoom(map, list)
					}
				}
			}
		}
	</script>
</body>

</html>